﻿# 调用方式示例： powershell.exe   .\replace_file_content.ps1 -p ".\config.ini" -sec "env_recorder" -key "recorder_ip" -str "192.168.100.100"
# 调用传递 如下参数
# -p 为相对参数，并且是文件路径，脚本会转换为绝对路径
# -key 修改的ip，这里只能是 "recorder_ip" or "env_hil"
# -st 转换后的字符串
# 最终直接在原始文件中修改了参数
param(
    $p,
    $sec,
    $key,
    $str
)

$path = Get-Item $p

$abs_path = join-path $path.DirectoryName $path.Name

if (-not (Test-Path $abs_path )){
    Write-Output "$abs_path 系统不存在此路径，请查验是否正确"
    sys.exit(-1)
}


#if ( $key -eq "recorder_ip" ){
#    $section = "env_recorder"
#}elseif ( $key -eq "hil_ip") {
#    $section = "env_hil"
#}

$section = $sec
echo "模块为：, $section"
echo "键为：, $key"


echo $abs_path
$file_path = $abs_path 
$substring2 = $st


# Windows API 函数声明
$ini = Add-Type -memberDefinition @"
[DllImport("Kernel32")] public static extern long WritePrivateProfileString (string section,string key,string val,string filePath);
[DllImport("Kernel32")] public static extern int GetPrivateProfileString (string section,string key,string def,StringBuilder retVal,int size,string filePath); 
"@ -passthru -name MyPrivateProfileString -UsingNamespace System.Text
# 调用 Windows API 函数
#$retVal=New-Object System.Text.StringBuilder(255)
#$null=$ini::GetPrivateProfileString($section,$key,"",$retVal,255,$file_path)

$substring1 =  $retVal.tostring()

#Write-Output "$section", "$retVal", "$null"
#Write-Output "$substring1", "$substring2"


Write-Output "传递的第一个参数：$p", "第二个：$sec", "第三个：$key", "第四个: $str"

$ret=$ini::WritePrivateProfileString($section, $key, $str, $file_path)

#Write-Output $so, $st
#$(Get-Content $file_path) -replace $substring1, $substring2
#$(Get-Content $file_path) -replace $substring1, $substring2 | Set-Content $file_path

